from PIL import Image
import numpy as np
from matplotlib import pyplot
import bisect

image_file = 'pbc17.tif'

def find_background_treshold(image_file):
    """Finds the treshold to extract background colour."""
    # First create an histogramm.
    image = Image.open(image_file).convert('L')
    
    histo = image.histogram()
    histo_lst = []
    
    for i in histo:
      histo_lst.append(i)
    
    # Get the maximum peak, this should be the background. Ignore peaks > 200
    max_value =  max(histo_lst[1:])
    # Get the histogram position of the peak.
    max_pos = histo_lst.index(max_value)
    
    #------------------------------------------------------------------------
    # Calculate the local minima
    a=np.array(histo_lst, dtype=np.float)
    
    gradients=np.diff(a)
    maxima_num=0
    minima_num=0
    max_locations=[]
    min_locations=[]
    count=0
    for i in gradients[:-1]:
        count+=1
    
        if ((cmp(i,0)>0) & (cmp(gradients[count],0)<0) & (i != gradients[count])):
            maxima_num+=1
            max_locations.append(count)     
    
        if ((cmp(i,0)<0) & (cmp(gradients[count],0)>0) & (i != gradients[count])):
            minima_num+=1
            min_locations.append(count)
        
    #------------------------------------------------------------------------
    # Get the next local maxima after the highest peak. This is the treashold.
    index= bisect.bisect_right(min_locations, max_pos)
    if index == 0: # there's not a "next lower value"
        raise NotImplementedError # you must decide what to do here
    else:
        return min_locations[index]

def get_pixels(image_file, treshold):
    """Get image pixels and replace all pixel below treshold with 0."""
    im = Image.open(image_file)
    if im.mode != 'L': 
        im = im.convert('L')
    pixels = list(im.getdata())
    outpixels = []
    counter = 0
    w, h = im.size
    f = open('out.txt', 'w')
    for i in pixels:
        if i < treshold:
            i = 0
        f.write(str(i) + '\t')
        if counter == int(w):
            f.write(str(i) + '\n')
            counter = 0
        counter += 1
        outpixels.append(i)
    
    outimg = Image.new('L', (w, h)) 
    outimg.putdata(outpixels)
    outimg.save('out.jpg')
        
def get_lanes():
    """Calculates sum of coloumns and draw a plot. Peaks are lanes."""
    treshold = find_background_treshold(image_file)
    
    get_pixels(image_file, treshold)
    array = np.asarray(Image.open('out.jpg'))
    
    im = Image.open(image_file)
    w, h = im.size
    y = array[0].sum()
    lanes = []
    for x in range(w):
        
        try:
            z = array[:, x].sum()
            lanes.append(z)
        except:
            pass
#    for i in lanes:
#        print i
    pyplot.plot(lanes)
    pyplot.show()
    print lanes.count(0)


get_lanes()





